package isstra.rendezvous;

public class ExchangerMJ<T> implements Exchanger<T> {
	private T dato;
	private boolean partner = false, rilascio = false;
	private Object lock = new Object();
	public T exchange( T msg ){
		synchronized( lock ){
			while( rilascio )//protezione per rientro "veloce"
				try{ lock.wait(); } catch(InterruptedException e){}
			T t=null;
		   	if( !partner ){
				dato = msg; partner = true;
				while( partner )
					try{ lock.wait(); }catch(InterruptedException e){}
				t = dato;	rilascio = false;
				lock.notifyAll();
			}
		   	else{ //partner==true
			    t = dato; dato = msg; partner = false; rilascio = true;
				lock.notifyAll();
			}
			return t;
		}
	}//exchange
}//ExchangerMJ
